import React from "react";
import {
  Pressable,
  View,
  Text,
  StyleSheet,
  TouchableWithoutFeedback,
} from "react-native";
import {
  OverlayContainer,
  useOverlayPosition,
  OverlayProvider
} from "@react-native-aria/overlays";

function CloseButton(props: any) {
  return (
    <TouchableWithoutFeedback
      onPress={props.onClose}
      accessible={false}
      importantForAccessibility={"no-hide-descendants"}
    >
      <View style={StyleSheet.absoluteFill}></View>
    </TouchableWithoutFeedback>
  );
}

const OverlayContent = ({ targetRef }) => {
  let overlayRef = React.useRef(null);
  const { overlayProps } = useOverlayPosition({
    placement: "bottom",
    targetRef,
    overlayRef,
  });

  return (
    <View
      ref={overlayRef}
      style={{
        backgroundColor:'white',
        position: "absolute",
        ...overlayProps.style,
      }}
    >
      <Text style={{backgroundColor:"gray",color:"white",padding:5}}>This content will be mounted in OverlayProvider</Text>
    </View>
  );
};

export function OverlayContainerDemo(props: any) {
  const [visible, setVisible] = React.useState(false);

  let ref = React.useRef(null);

  return (
    <OverlayProvider>
      <View style={{ marginLeft: "auto", marginRight: "auto",marginBottom:visible?100:0 }}>
        <Pressable
          ref={ref}
          accessibilityRole="button"
          onPress={() => setVisible(!visible)}
          style={{
            backgroundColor: "#fe4b83",
            maxWidth: 200,
            padding: 10,
            justifyContent: "center",
            alignItems: "center",
          }}
        >
          <Text>OverlayDemo Press me</Text>
        </Pressable>
        {visible && (
          <OverlayContainer>
            <CloseButton onClose={() => setVisible(!visible)} />
            <OverlayContent targetRef={ref} />
          </OverlayContainer>
        )}
      </View>
    </OverlayProvider>
  );
}
